/*
 * Copyright 2011 group coding kata nantes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package fr.coding.kata.nantes.roman.sylvain;

import java.util.HashMap;

import fr.coding.kata.nantes.roman.commons.RomanToNumeralsInterface;

public class RomanToNumerals implements RomanToNumeralsInterface {

    private static final HashMap<Character, Integer> TO_INTEGER = new HashMap<Character, Integer>();
    static {
        TO_INTEGER.put('I', 1);
        TO_INTEGER.put('V', 5);
        TO_INTEGER.put('X', 10);
        TO_INTEGER.put('L', 50);
        TO_INTEGER.put('C', 100);
        TO_INTEGER.put('D', 500);
        TO_INTEGER.put('M', 1000);
    }

    private String romanNumber;

    @Override
    public RomanToNumeralsInterface with(final String romans) {
        romanNumber = romans;
        return this;
    }

    @Override
    public Integer call() {
        int numeral = 0;
        final char[] letters = romanNumber.toCharArray();

        int previous = -1;
        for (int i = letters.length; i > 0;) {
            final char letter = letters[--i];

            final int currentLetterValue = toInteger(letter);
            if (previous > currentLetterValue) { // IV = 5 - 1 = 4
                numeral = numeral - currentLetterValue;
            } else { // VI = 5 + 1 = 6
                numeral = numeral + currentLetterValue;
            }
            previous = currentLetterValue;
        }

        return numeral;
    }

    private int toInteger(final char letter) {
        return TO_INTEGER.get(letter);
    }
}
